'use strict';
var _ = require('underscore');
var suquelizeService = require('../utils/sequelizeService');
var auth = require('../authControllers/user');
var Category = suquelizeService.models.Category;
var resJson = require('../utils/resJson.js');

var controller = {

};

//获取栏目
controller.getCategorys = {
  route: 'categorys',
  paramUrl: ['', '/:id'],
  action: function(req, res, next) {
    //没有带任何参数，获取所有
    var getArt = null;
    if (_.isEmpty(req.params)) {
      getArt = Category.fetch();
    } else {
      var id = parseInt(req.params.id);
      var type = req.params.type;
      if (id) {
        getArt = Category.findById(id);
      } else {
        return resJson(res, null, '错误的参数');
      }
    }

    getArt.then(function(_cat) {
        return resJson(res, _cat);
      })
      .catch(function(err) {
        return resJson(res, null, err);
      });
  }
};

//删除栏目
controller.delCategory = {
  method: 'delete',
  route: 'categorys',
  paramUrl: '/:id',
  filter: auth.loginCheckByAjax,
  action: function(req, res, next) {
    var id = parseInt(req.params.id);
    if (id) {
      Category.destroy({
          where: {
            id: id
          }
        })
        .then(function(_cat) {
          return resJson(res, _cat);
        })
        .catch(function(err) {
          return resJson(res, null, '删除栏目失败');
        });
    } else {
      return resJson(res, null, '错误的参数');
    }
  }
};

//修改栏目
controller.updCategory = {
  method: 'put',
  route: 'categorys',
  paramUrl: '/:id',
  filter: auth.loginCheckByAjax,
  action: function(req, res, next) {
    var id = parseInt(req.params.id);
    if (id && !_.isEmpty(req.body)) {
      var input = req.body;
      Category.findById(id)
        .then(function(_cat) {
          if (!_cat) {
            return resJson(res, null, '栏目已被删除');
          } else {
            return _cat.update(input);
          }
        })
        .then(function(_cat) {
          return resJson(res, _cat);
        })
        .catch(function(err) {
          return resJson(res, null, '更新栏目失败');
        });
    } else {
      return resJson(res, null, '错误的参数');
    }
  }
}

//新增栏目
controller.insCategory = {
  method: 'post',
  route: 'categorys',
  filter: auth.loginCheckByAjax,
  action: function(req, res, next) {
    if (!_.isEmpty(req.body)) {
      var input = req.body;
      Category.create(input)
        .then(function(_cat) {
          return resJson(res, _cat);
        })
        .catch(function(err) {
          return resJson(res, null, err);
        });
    } else {
      return resJson(res, null, '错误的参数');
    }
  }
}

module.exports = controller;
